import crypto from 'crypto'

const key = Buffer.from(process.env.NODE_KOA_KEY, 'utf8')
const iv = Buffer.from(process.env.NODE_KOA_IV, 'utf8')

/** 生成 uuid */
export const uuid = () => {
  return crypto.randomUUID().split('-').join('')
}

/**
 * 加密
 * @param sign 需要加密的参数
 * @returns 加密后的字符串
 */
export const genSign = (sign: unknown): string => {
  const newSign: string = JSON.stringify(sign)
  const cipher = crypto.createCipheriv(process.env.NODE_KOA_LANG, key, iv)
  let value = cipher.update(newSign, 'utf8', 'hex')
  value += cipher.final('hex')
  return value
}

/**
 * 解密
 * @param sign 需要解密的字符集
 * @returns 解密后的明文
 */
export const deSign = (sign: string) => {
  const decipher = crypto.createDecipheriv(process.env.NODE_KOA_LANG, key, iv)
  let value = decipher.update(sign, 'hex', 'utf8')
  value += decipher.final('utf8')
  return JSON.parse(value)
}

/**
 * 无法解密的加密
 * @param {String} text 需要加密的明文
 * @param {String} key 加密 key
 * @returns 加密后的字符串
 */
export const hmac = (text: string, key = '李香兰'): string => {
  return crypto.createHmac('sha1', key).update(text).digest('hex')
}
